<script>
import addtable from '@/mixins/addtable'
import AjaxStore from '@/utils/store/proxyAjax'
import store from './store.js'
import DialogForm from '@/components/DialogForm'
import Form from '@/components/Form'
import ButtonList from '@/components/ButtonList'
import qs from 'qs'

export default {
  name: 'deployment',
  mixins: [addtable, store],
  data() {
    const acceptFileType = '.bpmn'
    const validateFile = (rule, value, callback) => {
      if (this.file) {
        callback()
      } else {
        callback(new Error('请选择要上传的发布流程图'))
      }
    }
    return {
      tableSelectionCol: false,
      tableOptWidth: '80',
      labelWidth: '100px',
      file: '',
      fileList: [],
      idKey: 'deploymentId',
      delIdKey: 'deploymentId',
      addUrl: '/v1/activiti/deployment/loadBpmn',
      delUrl: '/v1/activiti/deployment/delete',
      store: new AjaxStore({
        url: '/v1/activiti/deployment/query'
      }),
      columns: [
        {
          prop: 'id',
          label: '发布ID',
          sortable: true,
          'min-width': '140',
          'show-overflow-tooltip': true,
          'header-align': 'center'
        },
        {
          prop: 'name',
          label: '发布名称',
          sortable: true,
          'min-width': '140',
          'show-overflow-tooltip': true,
          'header-align': 'center'
        },
        {
          prop: 'category',
          label: '类别',
          sortable: true,
          'min-width': '140',
          'show-overflow-tooltip': true,
          'header-align': 'center'
        },
        {
          prop: 'key',
          label: '关键字',
          sortable: true,
          'min-width': '140',
          'show-overflow-tooltip': true,
          'header-align': 'center'
        },
        {
          prop: 'deploymentTime',
          label: '发布时间',
          sortable: true,
          width: '155',
          'header-align': 'center'
        }
      ],
      searchFields: [
        {
          label: '发布名称',
          prop: 'deploymentName',
          placeholder: '请输入发布名称',
          anchor: 9
        },
        {
          label: '关键字',
          prop: 'deploymentKey',
          placeholder: '请输入关键字',
          anchor: 9
        }
      ],
      searchModel: {
        deploymentName: '',
        deploymentKey: ''
      },
      searchBtnList: this.searchBtns,
      toolPanelBtnList: this.toolPanelBtns,
      tableRowBtnList: this.tableRowBtns,
      formPanel: {
        add: {
          model: {
            file: '',
            name: '',
            key: '',
            category: ''
          },
          fields: [
            {
              label: '发布的流程',
              prop: 'file',
              anchor: 6,
              cursor: 'pointer',
              xType: 'slot',
              template: (
                <c-upload
                  class='upload'
                  ref='addUpload'
                  auto-upload={false}
                  accept={acceptFileType}
                  action=''
                  list-type='picture'
                  file-list={this.fileList}
                  {...{
                    props: {
                      onChange: this.handleFileChange,
                      onRemove: this.handleFileRemove
                    }
                  }}>
                  <c-button size='small' type='primary'>
                    点击上传
                  </c-button>
                  <div class='tip'>只能上传bpmn文件，且不超过500kb</div>
                </c-upload>
              )
            },
            {
              label: '发布名称',
              prop: 'name',
              placeholder: '请输入发布名称',
              anchor: 24,
              disabled: false
            },
            {
              label: '关键字',
              prop: 'key',
              placeholder: '请输入关键字',
              anchor: 24,
              disabled: false
            },
            {
              label: '分类',
              prop: 'category',
              placeholder: '请输入分类',
              anchor: 24,
              disabled: false
            }
          ],
          rules: {
            file: [
              { required: true, validator: validateFile, trigger: 'blur' }
            ],
            name: [
              { required: true, message: '请输入发布名称', trigger: 'blur' }
            ]
          },
          title: '发布流程',
          type: 'ADD',
          ref: 'addForm',
          submitBtnList: this.addBtns
        }
      }
    }
  },
  methods: {
    handleDelete(row) {
      return this.$confirm(
        '此操作不能回退，确认要删除您选中的数据么?',
        '提示',
        {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning'
        }
      )
        .then(() => {
          const params = {}
          params[this.delIdKey] = row['id']
          return this.del(params)
        })
        .then(({ success, message }) => {
          this.$message({
            type: success ? 'success' : 'error',
            message: message
          })
          if (success) {
            this.$refs.table.load(1)
          }
          setTimeout(() => {
            document.activeElement.blur()
          }, 300)
        })
        .catch(error => {
          setTimeout(() => {
            document.activeElement.blur()
          }, 300)
          this.$message({
            type: error === 'cancel' ? 'info' : 'error',
            message: error === 'cancel' ? '已取消删除' : error
          })
          // return Promise.reject(error)
        })
    },
    handleCancel() {
      this.dialogType = ''
      this.$refs.addUpload && this.$refs.addUpload.clearFiles()
      this.formPanel.add.model.file = ''
    },
    handleAdd() {
      this.dialogType = this.formPanel.add.type
      this.$nextTick(() => {
        this.$refs.addForm && this.$refs.addForm.resetFields()
      })
    },
    handleFileChange(file, fileList) {
      const isLt500kb = file.size / 1024 < 500
      if (!isLt500kb) {
        this.$message.error('上传文件大小不能超过 500kb!')
        if (fileList.length > 1) {
          fileList.splice(1)
        } else {
          fileList.splice(0)
        }
        return
      }
      this.file = file.raw
      this.formPanel.add.model.file = this.file
      if (fileList.length > 1) {
        // 只上传一个
        fileList[0] = fileList[1]
        fileList.splice(1)
      }
    },
    handleFileRemove() {
      this.file = ''
      this.formPanel.add.model.file = ''
    },
    handleCurrentChange() {},
    handleAddSubmit() {
      const params = {
        name: this.formPanel.add.model.name,
        category: this.formPanel.add.model.category,
        key: this.formPanel.add.model.key,
        logFlag: 1
      }
      const formData = new FormData()
      formData.append('file', this.formPanel.add.model.file)
      return this.$refs.addForm
        .validate()
        .then(() => {
          this.$refs.addFormSubmitBtns.handleChangeStatus('handleAddSubmit', {
            loading: true,
            icon: ''
          })
          return this.add(formData, params)
        })
        .then(({ success }) => {
          this.$message({
            type: success ? 'success' : 'error',
            message: success ? '发布流程成功！' : '发布流程失败！'
          })
          this.$refs.addFormSubmitBtns.handleChangeStatus('handleAddSubmit', {
            loading: false,
            icon: ''
          })
          if (success) {
            this.$refs.table.load(1)
            this.dialogType = ''
          } else {
            throw new Error('发布流程失败！')
          }
        })
        .catch(err => {
          this.$refs.addFormSubmitBtns &&
            this.$refs.addFormSubmitBtns.handleChangeStatus('handleAddSubmit', {
              loading: false,
              icon: ''
            })
          console.log(err)
          // return Promise.reject(err)
        })
    },
    // eslint-disable-next-line
    renderDialogForm(h) {
      return this._l(this.formPanel, item => {
        return (
          <DialogForm
            width='660px'
            class='activiti-flow-dialog'
            key={item.type}
            visible={this.dialogType === item.type}
            title={item.title}
            on-close={this.handleCancel}>
            <Form
              ref={item.ref}
              items={item.fields}
              inline={false}
              props-model={item.model}
              labelWidth={this.labelWidth}
              rules={item.rules}></Form>
            <c-form ref='form' slot='footer'>
              <c-form-item class='submit-btn'>
                <ButtonList
                  ref={`${item.ref}SubmitBtns`}
                  operateBtnList={item.submitBtnList}></ButtonList>
              </c-form-item>
            </c-form>
          </DialogForm>
        )
      })
    }
  },
  beforeCreate() {
    // 根据页面路由找出有权限访问的 url 数组
    const urlArr = ((this.$route.meta && this.$route.meta.children) || []).map(
      item => item.url
    )

    this.searchBtns = [
      {
        label: '查询',
        methods: 'handleSearch',
        url: '/v1/activiti/deployment/query',
        icon: 'el-icon-search',
        type: 'primary',
        disabled: false
      },
      {
        label: '重置',
        methods: 'handleSearchReset',
        url: '',
        icon: 'el-icon-refresh',
        type: 'warning',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.toolPanelBtns = [
      {
        label: '发布流程',
        methods: 'handleAdd',
        url: '/v1/activiti/deployment/loadBpmn',
        icon: 'el-icon-circle-plus-outline',
        type: 'primary',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.tableRowBtns = [
      {
        label: '删除',
        methods: 'handleDelete',
        url: '/v1/activiti/deployment/delete',
        icon: 'el-icon-delete',
        type: 'danger',
        key: 'delete',
        align: 'top-start',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.addBtns = [
      {
        label: '提交',
        methods: 'handleAddSubmit',
        url: '/v1/activiti/deployment/loadBpmn',
        icon: 'el-icon-circle-check-outline',
        type: 'primary',
        disabled: false
      },
      {
        label: '取消',
        methods: 'handleCancel',
        url: '',
        icon: 'el-icon-circle-close-outline',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)
  }
}
</script>

<style lang="scss">
.deployment {
  box-sizing: border-box;
  .searchPanel {
    padding-bottom: 0;
    .search-btn-box {
      bottom: 0;
    }
  }
}
.activiti-flow-dialog {
  .upload {
    .el-upload {
      display: flex;
      .tip {
        color: #f68686;
        margin-left: 5px;
        font-size: 14px;
      }
    }
  }
}
</style>
